package com.ifast.sys.controller;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Objects;
import com.ifast.common.annotation.Log;
import com.ifast.common.base.AdminBaseController;
import com.ifast.common.domain.DictDO;
import com.ifast.common.domain.Tree;
import com.ifast.common.service.DictService;
import com.ifast.common.utils.GjpLogger;
import com.ifast.common.utils.MD5Utils;
import com.ifast.common.utils.Result;
import com.ifast.common.utils.ShiroUtils;
import com.ifast.sys.config.SysConfig;
import com.ifast.sys.domain.DeptDO;
import com.ifast.sys.domain.RoleDO;
import com.ifast.sys.domain.UserDO;
import com.ifast.sys.service.DeptService;
import com.ifast.sys.service.RoleService;
import com.ifast.sys.service.UserService;
import com.ifast.sys.vo.UserVO;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <pre>
 * </pre>
 * 
 * <small> 2018年3月23日 | Aron</small>
 */
@RequestMapping("/sys/user")
@Controller
public class UserController extends AdminBaseController {
    private String prefix = "sys/user";

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    DictService dictService;
    
    @Autowired
    DeptService deptService;

    @Autowired
    SysConfig sysConfig;

    @Log("进入系统用户列表页面")
    @GetMapping("userTree")
    public String userTree(Model model) {
        return prefix + "/userTree";
    }

    @Log("进入系统用户列表页面")
    @RequiresPermissions("sys:user:user")
    @GetMapping("userPage")
    public String userPage(Model model,String deptId) {
        model.addAttribute("deptId",deptId);
        model.addAttribute("gly",Objects.equal(ShiroUtils.getSysUser().getDeptId(),"1"));
        return prefix + "/user";
    }
    
    @Log("查询系统用户列表")
    @GetMapping("/list")
    @ResponseBody
    public Result<Page<UserDO>> list(UserDO userDTO) {
        // 查询列表数据
        if(StrUtil.isBlank(userDTO.getDeptId())){
            userDTO.setDeptId(ShiroUtils.getSysUser().getDeptId());
        }
        DeptDO deptDO = this.deptService.selectById(userDTO.getDeptId());
        userDTO.setDwCode(deptDO.getDwCode());
        Page<UserDO> pageData = userService.listPage(getPage(UserDO.class),userDTO);
        return Result.ok(pageData);
    }

    
    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add/{deptId}")
    public String add(Model model,@PathVariable("deptId") String deptId) {
        DeptDO deptDO = deptService.selectById(deptId);
        Integer jibie = deptDO.getDwCode().length()/4;
        Wrapper<RoleDO> wrapper = new EntityWrapper<RoleDO>();
        if((jibie-1) != 0){
            wrapper.eq(true,"levelj",jibie-1);
        }
        List<RoleDO> roles = roleService.selectList(wrapper);
        model.addAttribute("roles", roles);
        model.addAttribute("deptId", deptId);
        model.addAttribute("deptName", deptDO.getName());
        return prefix + "/add";
    }

    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") Long id) {
        UserDO userDO = userService.selectById(id);
        model.addAttribute("user", userDO);
        DeptDO deptDO = deptService.selectById(userDO.getDeptId());
        List<RoleDO> roles = this.roleService.findListByUserId(id,deptDO);;
        model.addAttribute("roles", roles);
        return prefix + "/edit";
    }

    @RequiresPermissions("sys:user:add")
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    public Result<String> save(UserDO user) {
        user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
        DeptDO deptDO = this.deptService.selectById(user.getDeptId());
        user.setDwCode(deptDO.getDwCode());
        user.setMobile(user.getUsername());
        boolean flag = userService.insert(user);
        if(flag){
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    public Result<String> update(UserDO user) {
        boolean flag = userService.updateById(user);
        if(flag){
            return Result.ok();
        }else{
            return Result.fail();
        }
    }

    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    public Result<String> updatePeronal(UserDO user) {
        userService.updatePersonal(user);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    Result<String> remove(Long id) {
        userService.deleteById(id);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    public Result<String> batchRemove(@RequestParam("ids[]") Long[] userIds) {
        userService.deleteBatchIds(Arrays.asList(userIds));
        return Result.ok();
    }
    
    @Log("退出")
    @PostMapping("/exit")
    @ResponseBody
    public boolean exit(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exit(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("请求更改用户密码")
    @GetMapping("/resetPwd/{id}")
    public String resetPwd(@PathVariable("id") Long userId, Model model) {

        UserDO userDO = new UserDO();
        userDO.setId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    public Result<String> resetPwd(UserVO userVO) {
        userService.resetPwd(userVO, getUser());
        return Result.ok();
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    public Result<String> adminResetPwd(UserVO userVO) {
        userService.adminResetPwd(userVO);
        return Result.ok();

    }
    
    @Log("查询系统用户属性树形数据")
    @GetMapping("/tree")
    @ResponseBody
    public Tree<DeptDO> tree() {
        Tree<DeptDO> tree = new Tree<DeptDO>();
        tree = userService.getTree();
        return tree;
    }
    
    @Log("进入系统用户树形显示页面")
    @GetMapping("/treeView")
    public String treeView() {
        return prefix + "/userTree";
    }
    
    @Log("进入个人中心")
    @GetMapping("/personal")
    public String personal(Model model) {
        UserDO userDO = userService.selectById(getUserId());
        model.addAttribute("user", userDO);
        List<DictDO> hobbyList = dictService.getHobbyList(userDO);
        model.addAttribute("hobbyList", hobbyList);
        List<DictDO> sexList = dictService.getSexList();
        model.addAttribute("sexList", sexList);
        return prefix + "/personal";
    }
    
    @Log("上传头像")
    @ResponseBody
    @PostMapping("/uploadImg")
    public Result<?> uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request)
            throws Exception {
        Map<String, Object> result = new HashMap<>();
        result = userService.updatePersonalImg(file, avatar_data, getUserId());
        return Result.ok(result);
    }

    @PostMapping("/selectUserByIds")
    @ResponseBody
    public Result<List<UserDO>> selectUserByIds(@RequestParam("ids[]") Long[] userIds) {
        Result<List<UserDO>> result = new Result<List<UserDO>>();
        List<UserDO> list = userService.selectBatchIds(Arrays.asList(userIds));
        result.setData(list);
        return result;
    }


    @GetMapping("/getExcelFile")
    @ResponseBody
    public void getExcelFile(HttpServletResponse response) {
        try {
            com.ifast.common.utils.FileUtil.fileDownload(response,sysConfig.getFilePath()+"用户导入模板.xlsx","用户导入模板.xlsx");
        } catch (Exception e) {
            GjpLogger.error(e.toString(),e);
        }
    }

    @PostMapping("/excelExportFile")
    @ResponseBody
    public Result<Map<String,Integer>> excelExportFile(HttpServletRequest request) {
        Result<Map<String,Integer>> result = Result.ok();
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            MultipartFile file = multiRequest.getFile(iter.next());
            if (file == null) {
                result.setCode(Result.CODE_FAIL);
                result.setMsg("导入文件错误");
                return result;
            }
            DeptDO deptDO = this.deptService.selectById(ShiroUtils.getSysUser().getDeptId());
            try {
                Map<String,Integer> map = this.userService.importUser(file,deptDO);
                result.setData(map);
            } catch (Exception e) {
                GjpLogger.error(e.toString(),e);
                result.setCode(Result.CODE_FAIL);
                result.setMsg("导入失败!");
            }
        }
        return result;
    }
}
